package com.star.common.orm.typehandlers;

import cn.hutool.core.util.StrUtil;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * 类型转换：Varchar <-> Long[]，使用英文逗号,分割
 *
 * @author Jensen #公众号：架构师修行录
 * @date 2021/9/12 14:52
 * @since jdk1.8
 */
@Slf4j
public class LongsTypeHandler extends BaseTypeHandler<Long[]> {

    public LongsTypeHandler() {
        log.info("### BASE-DATA : INIT LongsTypeHandler ###");
    }

    public void setNonNullParameter(PreparedStatement ps, int i, Long[] longs, JdbcType jdbcType) throws SQLException {
        if (longs == null || longs.length == 0) return;
        StringBuilder sb = new StringBuilder();
        for (Long l : longs) {
            sb.append(l).append(",");
        }
        sb.append("<END>");
        ps.setString(i, sb.toString().replace(",<END>", ""));
    }

    public Long[] getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String strings = rs.getString(columnName);
        if (StrUtil.isBlank(strings)) return null;
        String[] split = strings.split(",");
        List<Long> longs = Lists.newArrayList();
        for (String s : split) {
            longs.add(Long.valueOf(s));
        }
        return longs.toArray(new Long[]{});
    }

    public Long[] getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String strings = rs.getString(columnIndex);
        if (StrUtil.isBlank(strings)) return null;
        String[] split = strings.split(",");
        List<Long> longs = Lists.newArrayList();
        for (String s : split) {
            longs.add(Long.valueOf(s));
        }
        return longs.toArray(new Long[]{});
    }

    public Long[] getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String strings = cs.getString(columnIndex);
        if (StrUtil.isBlank(strings)) return null;
        String[] split = strings.split(",");
        List<Long> longs = Lists.newArrayList();
        for (String s : split) {
            longs.add(Long.valueOf(s));
        }
        return longs.toArray(new Long[]{});
    }

}
